/*
 _____                        _ ____    _____ ____   __   
|  ___|__  _ __ _ __ ___     | / ___|  | ____/ ___| / /_  
| |_ / _ \| '__| '_ ` _ \ _  | \___ \  |  _| \___ \| '_ \ 
|  _| (_) | |  | | | | | | |_| |___) | | |___ ___) | (_) |
|_|  \___/|_|  |_| |_| |_|\___/|____/  |_____|____/ \___/ 
                                                          
 author : lisniuse
*/

class FormJs {

	constructor (options = '') {  
		this.options = options;
		this.formId = this.options.formId;
		this.formObj = document.getElementById(this.formId);
		this.subButObj = document.getElementById(this.options.subButId);
		this.tFormSubObj = this.formObj.childNodes;
		this._getAllSubTag();
		this._listenOnClick();
		if ( this.options.isRefresh == false){ 
			this.formObj.onsubmit = function (e) {
			   	return false;
			};
		}
	}
	//Get all objects with name attributes from form obj
	_getAllSubTag () {
		this.formTags = [];
		for (var i = 0; i < this.tFormSubObj.length; i++) {
			if (this.tFormSubObj[i].name){
				this.formTags.push(this.tFormSubObj[i]);
			}
		}
	}
	//
	_getJsonForTags (){ 
		this.dataJson = {};
		for (var i = 0; i < this.formTags.length; i++) { 
			this.dataJson[this.formTags[i].name] = this.formTags[i].value;
		}
	}

	_listenOnClick (){
		var me = this;
		me.subButObj.onclick = function(){ 
            			me.options.onclick();
			me._getJsonForTags();
			me._sendData();
		};
	}

	_sendData () { 
		var me = this;  
		let getQueryBody = ( me.formObj.method.toUpperCase() === "GET" ? (this._convertJsonToHttpQuery(this.dataJson)) : null );
		let postQueryBody = ( me.formObj.method.toUpperCase() === "POST" ? (this._convertJsonToHttpQuery(this.dataJson)) : null );
		let requestUrl =  me.formObj.action + "?" + getQueryBody; 
		let requestOptions = {
			method : me.formObj.method.toUpperCase(),
			body : postQueryBody
		}
		fetch(requestUrl,requestOptions).then(function(response) {
		        if (response.status !== 200) {
		                me.options.callback('error', null, "FormJS : 存在一个问题，状态码为：" + response.status);
		                return;
		        }
		        response.text().then(function(data) {
		                me.options.callback('success', data, null);
		        });
		}).
		catch(function(err) {
		        me.options.callback('error', null, "Fetch 错误:" + err);
		});
	}

	 _convertJsonToHttpQuery(jsonObj = '') {
	 	let tempStr = "";
	 	for (let key in jsonObj)  tempStr += `${key}=${jsonObj[key]}&`; 
	     	return tempStr.substring(0,tempStr.length - 1); 
	}
}